$(function() {
	
	
	var settings = {
			logo:'.headwrap .logo',
			title:'.headwrap .title',
			menus:'.headwrap .menus ul',
			settings:'.headwrap .settings',
			menuSidebarTitle:'.menu-sidebar .menu-sidebar-title',
			menuSidebar:'.bodywrap .menu-sidebar',
			menuWrap:'.menu-sidebar .menu-wrap',
			main:'.main',
			mainBody:'.main .mainwrap' 
	};
	
	var Page = {};
	S.each(settings,function(k,v){
		Page['$'+k] = $(v);
	});
	Page.events = new S.Event();
	Page.router = new S.Router();
	Page.menus = new S.Map();
	var pageLoading = new S.PageLoading({text:'系统正在加载....',modal:true});
	pageLoading.show();
	
	//使用Router来控制页面跳转
	//Router在F5刷新后，还能保持停留在当前页面页不是回到系统首页
	var pageRoute  = function(hash){
		var mns = hash.split('/');
		var mMenu = Page.menus.get(mns[0]);
		Page.$menus.find('li.current').removeClass('current');
		Page.$menus.find('li[mid='+mMenu.code+']').addClass('current');
		
		if(mMenu.items){
			Page.$menuSidebar.show();
			Page.$main.css('margin-left','209px');
			var html = [];
			html.push('<ul class="menu-items">');
			S.each(mMenu.items, function(i,m) {
				html.push('<li mid="'+m.code+'"><a class="icons '+m.icon+'"></a> <a>'+m.name+'</a></li>	');
			});
			html.push('</ul>');
			Page.$menuWrap.html(html.join(''));
		}
		
		if(!mns[1]){
			if(mMenu.items){
				var hash = window.location.hash;
				hash = hash.replace('/','')+'/' + mMenu.items[0].code;
				Page.router.navigate(hash);
				return;
			}else{
				Page.$menuSidebar.hide();
				Page.$main.css('margin-left','4px');
				Page.$mainBody.html('<iframe src="'+mMenu.url+'" width="100%" height="100%" frameborder="no"/>');
			}
		}else{
			Page.$menuSidebarTitle.html(mMenu.name);
			var subMenu = Page.menus.get(mns[1]);
			if(!subMenu){
				Page.router.navigate(mMenu.code);
			}
			Page.$menuWrap.find('li[mid='+subMenu.code+']').addClass('current');
			Page.$mainBody.html('<iframe src="'+subMenu.url+'" width="100%" height="100%" frameborder="no"/>');
		}
	};
	
	$.ajax({
		url:'menus',
		type:'post',
		dataType:'text',
		success:function(data){
			menus = eval(data);
			S.each(menus, function(i,menu) {
				Page.$menus.append('<li mid='+menu.code+'><a>'+menu.name+'</a></li>');
				Page.menus.put(menu.code,menu);
				Page.router.add(menu.code,pageRoute);
				if(menu.items){
					S.each(menu.items, function(i,item) {
						Page.menus.put(item.code,item);
						Page.router.add(menu.code+'/'+ item.code,pageRoute);
					});
				}
			});
			if(window.location.hash){
				Page.router.start();
			}else{
				Page.router.navigate(menus[0].code);
			}
		},
		complete:function(e){
			pageLoading.hide.defer(pageLoading,400);
		}
	});

	//按钮事件
	Page.$menus.delegate('li','click',function(){
		var $this = $(this);
		Page.router.navigate($this.attr('mid'));
	});
	Page.$menuWrap.delegate('li','click',function(){
		var $this = $(this);
		var hash = window.location.hash.replace(/\/.*$/g, '');
		Page.router.navigate(hash+'/' + $this.attr('mid'));
	});
});